<?php

namespace app\index\controller\keywords;

use app\common\controller\Frontend;
use think\Db;
use Exception;

/**
 * 财务中心
 *
 * @icon fa fa-acount
 */
class Keywords extends Frontend
{

    protected $searchFields = 'username,keyword';

    /**
     * @var \app\admin\model\Keywords
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Keywords');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
           
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
	
	/**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
			$params = $this->request->post("row/a");
			if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
						
				$urls = trim($params['url']);
				$urls = explode(PHP_EOL, $urls);
				$keywords = trim($params['keyword']);
				$keywords = explode(PHP_EOL, $keywords);
			
				$params['username'] = $this->auth->username;
				$params['addtime'] = time();
				$params['consumetime'] = time();
				
                $result = false;
                Db::startTrans();
                try {
					$data = [];
					foreach($keywords as $k=>$v)
					{
						$params['keyword'] = $v;
						if(isset($urls[$k])) $params['url'] = $urls[$k];
						
						$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
						$validate = $name . '.add';
						$this->model->validateFailException(true)->validate($validate);
					
						$data[] = $params;
					}
					$result = $this->model->saveAll($data, false);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
        return $this->view->fetch();
    }
}
